<template>
  <view>
    <view class="search-box">
      <!-- 使用 uni-ui 提供的搜索组件 -->
        <uni-search-bar @input="input" :radius="100" cancelButton="none"></uni-search-bar>
    </view>
    
    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="searchResults.length !== 0">
      <!-- tap 避免自定义组件内部阻止事件冒泡 -->
      <viem class="sugg-item" v-for="(item,i) in searchResults" :key="i" @tap="gotoDetail(item.goods_id)">
        <view class="goods-name">{{item.goods_name}}</view>
        <uni-icons type="arrowright" size="16"></uni-icons>
      </viem>
      
    </view>
    
    <!-- 搜索历史 -->
    <view class="history-box" v-else>
      <!-- 标题区域 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="clean"></uni-icons>
      </view>
      <!-- 列表区域 -->
      <view class="history-list">
        <uni-tag :text="item" v-for="(item,i) in historys" :key="i" @click="gotoGoodsList(item)"></uni-tag>
        
      </view>
      
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        //延时器的 timerId
        timer: null,
        //搜索关键词
        kw: '',
        //搜索结果列表
        searchResults: [],
        //搜索关键词的历史记录
        historyList: []
      };
    },
   computed: {
     historys() {
       // 确保是数组，非数组转空数组
       const list = Array.isArray(this.historyList) ? this.historyList : []
       // 先浅拷贝再反转
       return [...list].reverse()
     }
   },
    onLoad() {
      // 先获取数据，若不存在则用 '[]'
      const rawData = uni.getAccountInfoSync('kw') || '[]' 
      // 确保是字符串再解析
      this.historyList = typeof rawData === 'string' 
       ? JSON.parse(rawData) 
        : rawData 
    },
    methods: {
      //input 输入事件的处理函数
      input(e) {
        
        clearTimeout(this.timer)
        
        this.timer = setTimeout(() => {
          this.kw = e
          this.getSearchList()
        }, 500)
      },
      async getSearchList() {
        // 判断搜索关键词是否为空
        if(this.kw.length === 0) {
          this.searchResults = []
          return
        }
        
       const {data: res} = await uni.$http.get('https://api-hmugo-web.itheima.net/api/public/v1/goods/qsearch', {query: this.kw})
       if(res.meta.status !== 200) return uni.$showMsg()
       this.searchResults = res.message
       // 查询到搜索建议后,调用方法保存搜索关键词
       this.saveSearchHistory()
      },
      gotoDetail(goods_id) {
        uni.navigateTo({
            // 指定详情页面的 URL 地址，并传递 goods_id 参数
            url: '/subpkg/goods_list/goods_list?goods_id=' + goods_id
          })
      },
      saveSearchHistory() {
        // 兜底：确保 historyList 是数组，非数组转空数组
        const list = Array.isArray(this.historyList)? this.historyList : []; 
        const set = new Set(list);
        set.delete(this.kw);
        set.add(this.kw);
        this.historyList = Array.from(set);
        uni.setStorageSync('kw', JSON.stringify(this.historyList));
      },
      
     clean() {
       this.historyList = []
       uni.setStorageSync('kw','[]')
     },
     gotoGoodsList(kw) {
       uni.navigateTo({
         url: '/subpkg/goods_list/goods_list?query=' + kw
       })
     }
     
    }
    
  }
</script>

<style lang="scss">
 .search-box {
   position: sticky;
   top: 0;
   z-index: 999;
 }
 .sugg-list {
   padding: 0 5px;
   .sugg-item {
     font-size: 12px;
     padding: 13px 0;
     border-bottom: 1px solid #efefef;
     display: flex;
     align-items: center;
     justify-content: space-between;
     .goods-name {
       //文字不允许换行（单行文字）
       white-space: nowrap;
       //溢出部分隐藏
       overflow: hidden;
       //文本溢出后，使用 ... 代替
       text-overflow: ellipsis;
       margin-right: 3px;
     }
   }
 }
 .history-box {
   padding: 0 5px;
   
   .history-title {
     display: flex;
     align-items: center;
     justify-content: space-between;
     height: 40px;
     font-size: 13px;
     border-bottom: 1px solid #efefef;
   }
   .history-list {
     display: flex;
     flex-wrap: wrap;
     
     .uni-tag {
       margin-top: 5px;
       margin-right: 5px;
     }
   }
 }
</style>
